var myDeviceID;
$(function(){ //DOM Ready

    function navigate(url)
    {
        window.location.href = url;
    }

    $(document).attr("title", "{{title}}");
    content_width = ({{widget_dimensions[0]}} + {{widget_margins[0]}}) * {{columns}} + {{widget_margins[0]}}
    $('.gridster').width(content_width)
    $(".gridster ul").gridster({
        widget_margins: [{{ widget_margins[0] }}, {{ widget_margins[1] }}],
        widget_base_dimensions: [{{ widget_dimensions[0] }}, {{ widget_dimensions[1] }}],
        avoid_overlapped_widgets: true,
        max_rows: {% if rows is defined %}{{ rows }}{% else %}15{% endif %},
        max_size_x: {{columns}},
        shift_widgets_up: false
    }).data('gridster').disable();

    // Add Widgets

    var gridster = $(".gridster ul").gridster().data('gridster');
    {% for widget in widgets%}
        gridster.add_widget('<li><div data-bind="attr: {style: widget_style}" class="widget widget-{{widget.parameters.widget_type}}-{{widget.id}}" id="{{widget.id}}">{{widget.html.replace('\'', '\\\'')}}</div></li>', {{widget.size[0]}}, {{widget.size[1]}}, {{widget.position[0]}}, {{widget.position[1]}})
    {% endfor %}


    var widgets = {}
    // Initialize Widgets
    {% for widget in widgets%}
        widgets["{{widget.id}}"] = new {{widget.parameters.widget_type}}("{{widget.id}}", "{{ base_url }}", "{{skin}}", {{widget.parameters}})
    {% endfor %}

    // Setup click handler to cancel timeout navigations

    $( ".gridster" ).click(function(){
        clearTimeout(myTimeout);
        if (myTimeoutSticky) {
            myTimeout = setTimeout(function() { navigate(myTimeoutUrl); }, myTimeoutDelay);
        }
    });

    // Set up timeout

    var myTimeout;
    var myTimeoutUrl;
    var myTimeoutDelay;
    var myTimeoutSticky = 0;
    if (location.search != "")
    {
        console.log("begin")
        var query = location.search.substr(1);
        var result = {};
        query.split("&").forEach(function(part) {
        var item = part.split("=");
        result[item[0]] = decodeURIComponent(item[1]);
        });

        if ("deviceid" in result)
        {
            myDeviceID = result.deviceid;
            try
            {
                setCookie('ADdevID', myDeviceID);
            }
            catch (e)
            {
                console.log(e);
            }
        }
        else
        {
            try
            {
                myDeviceID = getCookie('ADdevID');
            }
            catch (e)
            {
                console.log(e);
                myDeviceID = null;
            }
        }
        if ("timeout" in result && "return" in result)
        {
            url = result.return
            argcount = 0
            for (arg in result)
            {
                if (arg != "timeout" && arg != "return" && arg != "sticky")
                {
                    if (argcount == 0)
                    {
                        url += "?";
                    }
                    else
                    {
                        url += "&";
                    }
                    argcount ++;
                    url += arg + "=" + result[arg]
                }
            }
            if ("sticky" in result)
            {
                myTimeoutSticky = (result.sticky == "1");
            }
            myTimeoutUrl = url;
            myTimeoutDelay = result.timeout * 1000;
            myTimeout = setTimeout(function() { navigate(url); }, result.timeout * 1000);
        }
    }
    else
    {
        try
        {
            myDeviceID = getCookie('ADdevID');
        }
        catch (e)
        {
            console.log(e);
            myDeviceID = null;
        }
    }

    // Start listening for AD Events

    window.dashstream = new DashStream("{{ transport }}", location.protocol, document.domain, location.port, "{{ title }}", widgets);

});
